#include "configtablewidget.h"
#include <QDebug>
#include <QDir>

ConfigTableWidget::ConfigTableWidget(QTableWidget* tableWidget)
    : m_tableWidget(tableWidget) {
}

void ConfigTableWidget::configureTable(QString path) {
    // 加载并应用配置
    loadTableConfig(path);
}

void ConfigTableWidget::loadTableConfig(QString path) {
//    qDebug() << "Current path: " << QDir::currentPath();

//    QSettings settings("../config/BD_config.ini", QSettings::IniFormat);
    QSettings settings("../" + path, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");  // 设置为 UTF-8 编码

    // 获取列数
    int columnCount = settings.value("table/columnCount", 5).toInt();  // 默认42列
    m_tableWidget->setColumnCount(columnCount);

    // 读取表头文字
    for (int i = 0; i < columnCount; ++i) {
        QString headerText = settings.value(QString("table/header_%1").arg(i), QString("列%1").arg(i)).toString();
        m_tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(headerText));
    }

    // 设置列宽
    for (int i = 0; i < columnCount; ++i) {
        int columnWidth = settings.value(QString("table/column_width_%1").arg(i), 100).toInt();  // 默认宽度100
        m_tableWidget->setColumnWidth(i, columnWidth);
    }

    // 设置列的可见性
    for (int i = 0; i < columnCount; ++i) {
        bool visible = settings.value(QString("table/column_visible_%1").arg(i), true).toBool();  // 默认可见
        m_tableWidget->setColumnHidden(i, !visible);
    }
}

void ConfigTableWidget::saveTableConfig() {
    QSettings settings("config.ini", QSettings::IniFormat);

    // 保存列数
    settings.setValue("table/columnCount", m_tableWidget->columnCount());

    // 保存表头文字
    for (int i = 0; i < m_tableWidget->columnCount(); ++i) {
        QString headerText = m_tableWidget->horizontalHeaderItem(i)->text();
        settings.setValue(QString("table/header_%1").arg(i), headerText);
    }

    // 保存列宽
    for (int i = 0; i < m_tableWidget->columnCount(); ++i) {
        int columnWidth = m_tableWidget->columnWidth(i);
        settings.setValue(QString("table/column_width_%1").arg(i), columnWidth);
    }

    // 保存列的可见性
    for (int i = 0; i < m_tableWidget->columnCount(); ++i) {
        bool visible = !m_tableWidget->isColumnHidden(i);
        settings.setValue(QString("table/column_visible_%1").arg(i), visible);
    }
}
